package ru.mirent.handlers;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import ru.mirent.entity.listeners.allure.AllureTestLifecycleListener;
import ru.mirent.exceptions.CustomAssertionFailedError;
import ru.mirent.exceptions.CustomRuntimeException;

public class TestExceptionHandler implements TestExecutionExceptionHandler {

    /**
     * Метод вызывается в случае возникновения в тесте ошибки любого типа.
     */
    @Override
    public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) throws Throwable {
        System.out.printf("%s:%s:%s - %s/%s%n",
                "TestExceptionHandler",
                "TestExecutionExceptionHandler",
                "handleTestExecutionException",
                throwable.getClass().getSimpleName(),
                throwable.getLocalizedMessage());

        System.out.printf("%s = %s%n", CustomRuntimeException.class.getSimpleName(), throwable instanceof CustomRuntimeException);
        System.out.printf("%s = %s%n", CustomAssertionFailedError.class.getSimpleName(), throwable instanceof CustomAssertionFailedError);
        System.out.printf("%s = %s%n", Error.class.getSimpleName(), throwable instanceof Error);
        System.out.printf("%s = %s%n", RuntimeException.class.getSimpleName(), throwable instanceof RuntimeException);
        System.out.printf("%s = %s%n", Exception.class.getSimpleName(), throwable instanceof Exception);

        AllureTestLifecycleListener.getThrowableThreadLocal().set(throwable);

        throw throwable;
    }
}
